# coding=utf-8
__author__ = "tzz6"

import requests
import json
import urllib.request
import os
import sqlite3
import time
import re
from PIL import Image


def get_thumbnail(file_path):
    if file_path.split('.')[-1] == 'jpg' and file_path.split('.')[-2] != 'jpg':
        img = Image.open(file_path)
        w, h = img.size
        img.thumbnail(((int)(w / 4), (int)(h / 4)))
        img.save(file_path + '.jpg')
        return "缩略图生成完成..."
    else:
        return "缩略图已存在..."


def get_pic_from_bing():
    print('\n', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

    bingUrl = 'https://cn.bing.com'
    idx = 0  # 日期标志
    apiUrl = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=' + str(idx) + '&n=1&nc=1535091917942&pid=hp'
    r = requests.get(apiUrl)  # 获取到json
    r = json.loads(r.text)  # 转化为dict类型

    images = r['images'][0]
    print(images)

    startdate = images['startdate']
    fullstartdate = images['fullstartdate']
    enddate = images['enddate']
    url = images['url']
    urlbase = images['urlbase']
    copyright = images['copyright']
    copyrightlink = images['copyrightlink']
    title = images['title']
    quiz = images['quiz']
    wp = images['wp']
    hsh = images['hsh']

    print('处理前：' + url)
    image_name = re.split(r'\.(.*?)&', url)[1]
    url = url.split('&')[0]
    print('处理后：')
    print(url)
    print(image_name)

    if url[:4] == 'http':
        imageUrl = url  # 图片链接
    else:
        imageUrl = bingUrl + url

    image_dir_path = "../static/bing/images"
    rel_path = "Site/images"

    if not os.path.exists(image_dir_path) or os.path.isfile(image_dir_path):  # 判断文件夹是否存在
        os.makedirs(image_dir_path)

    save_path = image_dir_path + '/' + image_name  # 保存文件地址
    path = os.path.join(rel_path, image_name)

    def schedule(a, b, c):  # 下载进度
        per = 100.0 * a * b / c
        if per > 100:
            per = 100
        # print('%.2f %%' % per)

    print(imageUrl)
    print(save_path)
    if not os.path.exists(save_path):  # 判断图片是否已存在
        print("图片未下载")
        urllib.request.urlretrieve(imageUrl, save_path, schedule)
        print("图片下载完成...")
    else:
        print("图片已存在")

    print(get_thumbnail(save_path))
    # print("缩略图生成完成...")

    conn = sqlite3.connect("../../db.sqlite3")
    c = conn.cursor()

    insert_sql = "INSERT INTO bing2_images (startdate, fullstartdate, enddate, url, urlbase, copyright, copyrightlink, title, quiz, hsh, path) " \
                 "VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \
                 % (startdate, fullstartdate, enddate, url, urlbase, copyright, copyrightlink, title, quiz, hsh, path)
    # print(insert_sql)
    print(startdate, fullstartdate, enddate, url, urlbase, copyright, copyrightlink, title, quiz, hsh, path)

    r = c.execute("select * from bing2_images where enddate = " + enddate)
    if not r.fetchone():
        c.execute(insert_sql)
        conn.commit()
        print(enddate, " 插入完成")
    else:
        print(enddate, " 数据库信息已存在")
    result = c.execute("select * from bing2_images")

    # # 检索所有已存在日期图片
    # for r in result:
    #     # for l in range(len(r)):
    #     #     print(r[l], end="\n")
    #     print(r[3], end="\n")

    c.close()
    print("任务执行完毕！")


if __name__ == '__main__':
    get_pic_from_bing()
